<template>
  <div class="main_box" style="padding: 0 10px 10px 10px" v-if="dataInfo">
    <el-card class="header-card">
      <div slot="header">
        <div class="header" style="display: flex; justify-content: space-between">
          <div class="title">
            {{ dataInfo.businessName }}
            <el-dropdown trigger="click" size="mini" style="margin-left: 10px">
              <i class="el-icon-caret-bottom"></i>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="item in platformMerchantList" :key="item.id" @click.native="() => {
                    sharingRatioBusinessList = platformMerchantList.filter((_item) => _item.id !== item.id);
                    fetchObtainBusinessInfo(item.id);
                  }
                  ">{{ item.name }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div>
            <el-button type="primary" plain v-has="permissionAdd" @click="handleNavigateToRoute('新增')" size="mini"> 新增
            </el-button>
            <el-button type="success" plain v-has="permissionEdit" @click="handleNavigateToRoute('编辑')" size="mini">
              编辑
            </el-button>
            <el-button type="warning" plain v-has="permissionOpenUser" @click="handleClickOpenUser" size="mini"
                       v-if="dataInfo.businessState === 0"> 开通账号
            </el-button>
            <el-button type="warning" plain v-has="permissionBusinessServer" @click="handleNavigateToRoute('货品库')"
                       size="mini"> 货品库
            </el-button>
            <el-button type="warning" plain v-has="permissionViewGoods" @click="handleNavigateToRoute('查看经营产品')"
                       size="mini"> 经营产品
            </el-button>
            <el-dropdown trigger="click" size="mini" style="margin-left: 10px">
              <el-button type="info" plain icon="fa fa-list-ul" size="mini"> 更多</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionModifySharingRatio" @click.native="showSharingRatio = true">修改分成比例
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionAccount" v-if="dataInfo.accountState"
                                  @click="handleNavigateToRoute('收款账户')">收款账户
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionWeight" @click.native="handleWeight"> 设置权重</el-dropdown-item>
                <el-dropdown-item v-has="permissionSetDiscount" @click.native="showDiscount = true"> 设置折扣
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionCheckInfo" v-if="dataInfo.businessState"
                                  @click.native="handleClickBusinessAccount"> 查看账号信息
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionUnionWaiter" @click.native="handleAssoicateWaiter"> 关联公共服务员
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionSetAddress" @click.native="handleSetAddress">设置管理范围
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionDeliveryModel" @click.native="handleSetDeliveryModel">设置配送费模板
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionUpAllGoods" @click.native="handleClickUpAllGoods">上架所有产品
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>
      <el-row>
        <el-col class="right-info">
          <el-row class="header-info">
            <el-col class="header-img__wrapper">
              <!-- style="display:block;width: 100px;height: 100px;border-radius: 50px;overflow: hidden;" -->
              <el-image fit="cover" title="点击可预览" v-if="dataInfo.businessLogo" :src="dataInfo.businessLogo" alt=""
                        :preview-src-list="[dataInfo.businessLogo]"></el-image>
            </el-col>
            <el-col class="text-info">
              <el-col>
                <el-col>经营方式:</el-col>
                <el-col>{{ formatManageType(dataInfo.manageType) }}</el-col>
              </el-col>
              <el-col>
                <el-col>商户全称:</el-col>
                <el-col>{{ dataInfo.businessName }}</el-col>
              </el-col>
              <el-col>
                <el-col>联系人:</el-col>
                <el-col>{{ dataInfo.linkName }}</el-col>
              </el-col>
              <el-col>
                <el-col>联系电话:</el-col>
                <el-col>{{ dataInfo.linkPhone }}</el-col>
              </el-col>
              <el-col>
                <el-col>营业状态:</el-col>
                <el-col v-if="dataInfo.businessState>0">
                  <el-switch
                      v-model="businessState"
                      active-color="#13ce66"
                      inactive-color="#9C9C9E"
                      active-text="营业"
                      inactive-text="打烊"
                      @change="handleChangeBusinessState">
                  </el-switch>
                </el-col>
                <el-col v-else>
                  <span style="color:red;">未开通</span>
                </el-col>
              </el-col>
              <el-col>
                <el-col>创建时间:</el-col>
                <el-col>{{ dataInfo.createDate }}</el-col>
              </el-col>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="body-card">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <el-row class="info-module">
            <el-col class="title"> 核心信息</el-col>
            <el-col class="content">
              <el-row>
                <el-col>商户简称:</el-col>
                <el-col>{{ dataInfo.businessShortName }}</el-col>
              </el-row>
              <el-row>
                <el-col>商户昵称:</el-col>
                <el-col>{{ dataInfo.businessMiniName }}</el-col>
              </el-row>
              <el-row>
                <el-col> 服务分类:</el-col>
                <el-col>
                  {{ serverList.length > 0 ? serverList : '' }}
                </el-col>
              </el-row>
              <el-row>
                <el-col> 商户折扣比例:</el-col>
                <el-col>
                  <span>{{ dataInfo.discount }}%</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col> 打包费折扣比例:</el-col>
                <el-col>
                  <span>{{ dataInfo.packageDiscount }}%</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col> 语音商户:</el-col>
                <el-col>
                  <span v-if="dataInfo.voiceFlag"> 是{{ '(等级：' + dataInfo.voiceLevel + ')' }} </span>
                  <span v-else> 否 </span>
                </el-col>
              </el-row>
              <el-row>
                <el-col> 开通周边服务:</el-col>
                <el-col>
                  <span v-if="dataInfo.openFlag"> 已开通 </span>
                  <span v-else> 未开通 </span>
                </el-col>
              </el-row>
              <el-row>
                <el-col> 营业执照:</el-col>
                <el-col>
                  <el-image style="width: 150px" title="点击可预览" v-if="dataInfo.businessLicense"
                            :src="dataInfo.businessLicense" alt=""
                            :preview-src-list="[dataInfo.businessLicense]"></el-image>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row class="info-module">
            <el-col> 联系信息</el-col>
            <el-col>
              <el-row>
                <el-col> 联系地址:</el-col>
                <el-col>
                  {{ linkAddress }}
                </el-col>
              </el-row>
              <el-row>
                <el-col> 经纬度:</el-col>
                <el-col> {{ dataInfo.longitude }},{{ dataInfo.latitude }}</el-col>
              </el-row>
              <el-row>
                <el-col> 备用电话:</el-col>
                <el-col>
                  {{ dataInfo.linkPhoneTwo }}
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row class="info-module">
            <el-col> 业务信息</el-col>
            <el-col>
              <el-row>
                <el-col> 推广员:</el-col>
                <el-col>
                  {{ promoterName }}
                </el-col>
              </el-row>
              <el-row>
                <el-col> 维护员:</el-col>
                <el-col>
                  {{ keeperName }}
                </el-col>
              </el-row>
              <el-row>
                <el-col> 创建人:</el-col>
                <el-col>
                  {{ dataInfo.createUserName }}
                </el-col>
              </el-row>
              <el-row>
                <el-col> 修改人:</el-col>
                <el-col>
                  {{ dataInfo.modifyUserName }}
                </el-col>
              </el-row>
              <el-row>
                <el-col> 修改时间:</el-col>
                <el-col>
                  {{ dataInfo.modifyDate }}
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="营业信息" name="second">
          <el-row class="info-module">
            <el-col> 营业信息</el-col>
            <el-col class="content">
              <el-row>
                <el-col>自动营业或打烊:</el-col>
                <el-col>{{ dataInfo.autoOpen ? '是' : '否' }}</el-col>
              </el-row>
              <el-row>
                <el-col>支付后自动打印:</el-col>
                <el-col>{{ dataInfo.autoPrint ? '是' : '否' }}</el-col>
              </el-row>
              <el-row>
                <el-col>接单后自动打印:</el-col>
                <el-col>{{ dataInfo.autoAcceptPrint ? '是' : '否' }}</el-col>
              </el-row>
              <el-row>
                <el-col>自动接单:</el-col>
                <el-col>{{ dataInfo.autoAccept ? '是' : '否' }}</el-col>
              </el-row>
              <el-row>
                <el-col>超单数量</el-col>
                <el-col>{{ dataInfo.exceedOrderNum }}</el-col>
              </el-row>
              <el-row>
                <el-col>单次超时未结单时间</el-col>
                <el-col>{{ dataInfo.taskSingleTimeout }}分钟</el-col>
              </el-row>
              <el-row>
                <el-col>总次超时未结单时间</el-col>
                <el-col>{{ dataInfo.taskTotalTimeout }}</el-col>
              </el-row>
              <el-row>
                <el-col>服务员下班方式</el-col>
                <el-col>{{ dataInfo.workOffWay == 1 ? '可自动打卡下班' : '仅手动打卡下班' }}</el-col>
              </el-row>
              <el-row>
                <el-col>服务员接单方式</el-col>
                <el-col>{{ dataInfo.takeOrderWay == 1 ? '仅手动接单' : '可自动接单' }}</el-col>
              </el-row>
              <!-- <el-row>
								<el-col>起步价:</el-col>
								<el-col>{{ dataInfo.startPrice }}</el-col>
							</el-row> -->
              <el-row>
                <el-col>公共服务员配送比例:</el-col>
                <el-col>{{ dataInfo.percentage }}</el-col>
              </el-row>
              <el-row>
                <el-col>打包费折扣比例:</el-col>
                <el-col>{{ dataInfo.packageDiscount }}</el-col>
              </el-row>
              <el-row>
                <el-col>打印模板类型:</el-col>
                <el-col>{{ dataInfo.printModel ? '有价格' : '无价格' }}</el-col>
              </el-row>
              <el-row>
                <el-col>语音单类型:</el-col>
                <el-col>{{ formatVoiceFlag(dataInfo.voiceFlag) }}</el-col>
              </el-row>
              <el-row v-if="dataInfo.voiceFlag">
                <el-col>语音接单等级:</el-col>
                <el-col>{{ dataInfo.voiceLevel }}(等级范围：1-10)</el-col>
              </el-row>
              <el-row>
                <el-col>开通周边服务:</el-col>
                <el-col>{{ dataInfo.openFlag ? '是' : '否' }}</el-col>
              </el-row>
              <el-row>
                <el-col>支持线下月结</el-col>
                <el-col>{{ dataInfo.allowMonthSettle ? '是' : '否' }}</el-col>
              </el-row>
              <el-row>
                <el-col>开通电话提醒</el-col>
                <el-col>{{ dataInfo.allowOpenPhone ? '是' : '否' }}</el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row class="info-module">
            <el-col> 营业时间</el-col>
            <el-col class="content">
              <el-table :data="dataInfo.hours" style="width: fit-content; margin-bottom: 10px">
                <el-table-column type="index" width="100" align="center" label="序号"></el-table-column>
                <el-table-column label="开始时间" prop="beginHours" width="200" align="center"></el-table-column>
                <el-table-column label="结束时间" prop="endHours" width="200" align="center"></el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="提现资质" name="third" v-if="dataInfo.businessState">
          <el-row class="info-module">
            <el-col> 资质信息</el-col>
            <el-col class="content">
              <el-row>
                <el-col>用户类型:</el-col>
                <el-col>{{ accountInfo.userType == 1 ? '企业商户' : '个体工商户' }}</el-col>
              </el-row>
              <el-row>
                <el-col>提现方式:</el-col>
                <el-col>{{ accountInfo.cashType == 1 ? '提现至自有账户' : '提现至上级账户' }}</el-col>
              </el-row>
              <el-row>
                <el-col>提现天数:</el-col>
                <el-col>T+{{ accountInfo.cashDay }}天</el-col>
              </el-row>
              <el-row>
                <el-col>结算方式:</el-col>
                <el-col>{{ accountInfo.settleType == 1 ? '每日结算' : '每月结算' }}</el-col>
              </el-row>
              <el-row v-if="accountInfo.settleType == 2">
                <el-col>结算日:</el-col>
                <el-col>{{ accountInfo.settleDay }}</el-col>
              </el-row>
              <el-row>
                <el-col>真实姓名(法人):</el-col>
                <el-col>{{ accountInfo.fullName }}</el-col>
              </el-row>
              <el-row>
                <el-col>手机号(法人):</el-col>
                <el-col>{{ accountInfo.phone }}</el-col>
              </el-row>
              <el-row>
                <el-col>身份证号:</el-col>
                <el-col>{{ accountInfo.idCard }}</el-col>
              </el-row>
              <el-row>
                <el-col>身份证正面照:</el-col>
                <el-col>
                  <el-image style="width: 150px" title="点击可预览" v-if="accountInfo.idCardFront"
                            :src="accountInfo.idCardFront" alt=""
                            :preview-src-list="[accountInfo.idCardFront]"></el-image>
                </el-col>
              </el-row>
              <el-row>
                <el-col>身份证反面照:</el-col>
                <el-col>
                  <el-image style="width: 150px" title="点击可预览" v-if="accountInfo.idCardBack"
                            :src="accountInfo.idCardBack"
                            alt="" :preview-src-list="[accountInfo.idCardBack]"></el-image>
                </el-col>
              </el-row>
              <el-row>
                <el-col>企业名称:</el-col>
                <el-col>{{ accountInfo.businessName }}</el-col>
              </el-row>
              <el-row>
                <el-col>企业营业执照:</el-col>
                <el-col>
                  <el-image style="width: 150px" title="点击可预览" v-if="accountInfo.businessLicense"
                            :src="accountInfo.businessLicense" alt=""
                            :preview-src-list="[accountInfo.businessLicense]"></el-image>
                </el-col>
              </el-row>
              <el-row>
                <el-col>企业联系人姓名:</el-col>
                <el-col>{{ accountInfo.linkName }}</el-col>
              </el-row>
              <el-row>
                <el-col>企业联系人电话:</el-col>
                <el-col>{{ accountInfo.linkPhone }}</el-col>
              </el-row>
              <el-row>
                <el-col>用户开户状态:</el-col>
                <el-col>{{ formatOpenState(accountInfo.openState) }}</el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="经营范围" name="fourth">
          <el-row v-for="(item, index) in businessVillages" :key="item.type" style="margin-bottom: 20px">
            <div style="font-size: 14px; color: #1e6abc; margin-bottom: 10px">
              范围类型 ->
              <el-tag size="mini" effect="dark">
                {{ formatVillageType(item.type) }}
              </el-tag>
            </div>

            <el-table :data="item.villages" style="width: max-content">
              <el-table-column label="省市区" width="320" align="center" v-if="item.type == 2 || item.type == 4">
                <template slot-scope="scope">
                  <span>{{ scope.row.provinceName }}{{ scope.row.cityName }}{{ scope.row.areaName }}{{
                      scope.row.streetName
                    }}</span>
                </template>
              </el-table-column>
              <el-table-column label="小区" width="280" prop="villageName" align="center" v-if="item.type == 2">
              </el-table-column>
              <el-table-column label="呼叫器ID" prop="beeperIds" width="320" align="center" v-if="item.type == 1">
              </el-table-column>
              <el-table-column label="公里数" prop="kilometers" width="320" align="center" v-if="item.type == 3">
              </el-table-column>
              <el-table-column label="起步价" prop="startPrice" width="200" align="center"></el-table-column>
            </el-table>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="其它信息" name="fifth">
          <el-row class="info-module">
            <el-col style="margin-bottom: 10px"> 营业信息</el-col>
            <el-row class="content">
              <el-table :data="banners">
                <el-table-column label="服务分类" width="100">
                  <!-- :src="item.url"
								fit="cover"
								:preview-src-list="formatUrl(list)" -->
                </el-table-column>
                <el-table-column label="轮播图">
                  <template slot-scope="scope">
                    <el-image style="margin-right: 10px" v-for="(item, index) in scope.row.list" :src="item.url"
                              :key="index" :preview-src-list="getImgUrlList(scope.row.list)"></el-image>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 修改分成比例	-->
    <el-dialog center title="修改分成比例" width="800px" :visible.sync="showSharingRatio">
      <el-form :model="sharingRatioForm" ref="sharingRatioForm" label-width="150px" :rules="roleRules"
               style="display: flex; flex-wrap: wrap; justify-content: space-between">
        <el-form-item label="分成平台商户:" prop="sharingBusinessId">
          <el-select v-model="sharingRatioForm.sharingBusinessId" clearable filterable>
            <el-option v-for="item in sharingRatioBusinessList" :value="item.id" :label="item.name" :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分成比例值(%):" prop="proportion">
          <el-input-number :min="0" :max="100" :controls="false"
                           v-model="sharingRatioForm.proportion"></el-input-number>
        </el-form-item>
        <el-form-item label="是否负责补贴账户:" prop="subsidyFlag" style="margin-bottom: 22px">
          <el-select v-model="sharingRatioForm.subsidyFlag" clearable filterable>
            <el-option :value="1" label="是"></el-option>
            <el-option :value="0" label="否"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="handleConfirmSharingRatio"> 保 存</el-button>
      </div>
    </el-dialog>

    <!-- 设置权重 -->
    <el-dialog center title="设置权重" width="400px" :visible.sync="showWeight">
      <div>
        <el-input type="number" v-model.number="weight" placeholder="请输入整数" clearable></el-input>
        <div style="color: red">说明：权重值越大，商户排序越靠前。平均值99，权重值范围：1-999999</div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="setWeight"> 保 存</el-button>
      </div>
    </el-dialog>

    <!-- 一键设置折扣 -->
    <el-dialog center title="一键设置折扣" width="400px" :visible.sync="showDiscount">
      <div>
        <el-form ref="form" :model="discountInfo" label-width="80px">
          <el-form-item label="修改类型">
            <el-radio-group v-model="discountInfo.discountType">
              <el-radio :label="1">商户比例折扣</el-radio>
              <el-radio :label="2">打包比例折扣</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="比例值(%)">
            <el-input placeholder="请输入比例值" v-model="discountInfo.val" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="operateDiscount(1)"> 保 存</el-button>
        <el-button type="default" @click="operateDiscount(2)"> 取 消</el-button>
      </div>
    </el-dialog>

    <!-- 开通账号 -->
    <template v-if="openUser.show">
      <el-dialog center title="开通账号" width="400px" :visible.sync="openUser.yes" :before-close="closeOpenUser">
        <el-form ref="openUser" :inline="true" label-width="100px" :model="openUser" :rules="openUserRules">
          <el-row style="padding-left: 100px; color: red; font-size: 14px"> 初始密码默认为123456</el-row>
          <el-form-item label="登录账号" prop="userName">
            <el-input v-model="openUser.userName"></el-input>
          </el-form-item>
          <el-form-item label="绑定手机号" prop="phone">
            <el-input type="number" v-model="openUser.phone"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button type="primary" @click="confirmOpenUser">开通</el-button>
          <el-button @click="openUser.show = false">取消</el-button>
        </div>
      </el-dialog>
    </template>

    <!-- 商户账户信息 -->
    <el-dialog center :visible.sync="businessAccount.show" title="商户账户">
      <el-table :data="businessAccount.list">
        <el-table-column label="用户姓名" prop="fullName" align="center"></el-table-column>
        <el-table-column label="登录账号" prop="userName" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleResetPassword(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 关联公共服务员 -->
    <el-dialog center :visible.sync="waiter.show" title="关联公共服务员" width="fit-content">
      <el-select style="width: 300px" placeholder="请选择服务员" v-model="waiter.waiterId" multiple>
        <el-option v-for="item in waiterList" :value="item.id" :label="item.name" :key="item.id"></el-option>
      </el-select>
      <div slot="footer">
        <el-button type="primary" @click="confirmAssoicateWaiter"> 确定</el-button>
        <el-button @click="waiter.show = false"> 取消</el-button>
      </div>
    </el-dialog>

    <!-- 设置管理范围 -->
    <SetAddress :show.sync="setAddress.show" :list="setAddress.list" @confirm="confirmSetAddress"
                :level="setAddress.level"></SetAddress>

    <!-- 设置经营范围配送费模板 -->
    <SetDeliveryModel v-model="deliveryModel.show" :list="deliveryModel.list" :modelList="deliveryModel.modelList"
                      @confirm="confirmSetDM"></SetDeliveryModel>
  </div>
</template>

<script>
import * as message from '@/constants/message';
import BusinessApi from '@/api/business/business';
import ServerClassifyApi from '@/api/server/serverClassify';
import LoginApi from '@/api/system/login';
import {Notification} from 'element-ui';
import AuthApi from '@/api/system/auth';
import AdminVillageApi from '../../../api/common/adminVillage';
import SetAddress from '../../../components/SetAddress.vue';
import DeliveryModelApi from '../../../api/business/deliveryModel';
import SetDeliveryModel from '../components/SetDeliveryModel.vue';
import TenantApi from '../../../api/system/tenant';

export default {
  components: {SetDeliveryModel, SetAddress},
  data() {
    return {
      dataInfo: undefined,
      businessState: true,
      platformMerchantList: [],
      serverList: [],
      servers: [],
      businessVillages: [],
      roleList: [],
      activeName: 'first',
      accountInfo: {},
      banks: [],
      banners: [],
      showSharingRatio: false,
      sharingRatioBusinessList: [],
      sharingRatioForm: {
        proportion: '',
        subsidyFlag: '',
        sharingBusinessId: '',
      },
      roleRules: {
        sharingBusinessId: [{required: true, message: '请选择平台商户', trigger: 'change'}],
        proportion: [{required: true, message: '请输入平台商户分成比例值', trigger: 'blur'}],
        subsidyFlag: [{required: true, message: '请选择是否负责补贴账户', trigger: 'change'}],
      },

      showWeight: false,
      weight: '',

      showDiscount: false,
      discountInfo: {
        val: '',
        discountType: 1,
      },

      openUser: {
        show: false,
        phone: '',
        yes: true,
        userName: ''
      },
      openUserRules: {
        userName: [{required: true, message: '请填写账号'}],
        phone: [
          {
            pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
            message: '电话号码格式错误',
            trigger: 'blur',
          },
        ],
      },

      waiter: {
        show: false,
        waiterId: [],
      },
      waiterList: [],

      businessAccount: {
        show: false,
        list: [],
        modelList: [],
      },

      setAddress: {
        show: false,
        list: [],
        level: 5,
      },

      deliveryModel: {
        show: false,
        // list:[]
      },

      permissionAdd: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_ADD',
      permissionEdit: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_EDIT',
      permissionWeight: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_WEIGHT',
      permissionSetDiscount: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_SETDISCOUNT',
      permissionOpenUser: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_OPEN_USER',
      permissionViewGoods: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_VIEW_GOODS',
      permissionUpAllGoods: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_UP_ALL_GOODS',
      permissionBusinessServer: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_BUSINESS_SERVER',
      permissionCheckInfo: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_CHECK_INFO',
      permissionUnionWaiter: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_UNION_WAITER',
      permissionDeliveryModel: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_DELIVERY_MODEL',
      permissionAccount: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_ACCOUNT',
      permissionSetAddress: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_SET_ADDRESS',
      permissionModifySharingRatio: 'SYSTEM_MANAGER_BUSINESS_PLATFORM_MODIFY_SHARING_RATIO',
    };
  },
  computed: {
    // 把省市区和详细地址合并起来为联系地址
    linkAddress() {
      let streetName = this.dataInfo.streetName ? this.dataInfo.streetName : '';
      let address = this.dataInfo.address ? this.dataInfo.address : '';
      return this.dataInfo.provinceName + this.dataInfo.cityName + this.dataInfo.areaName + streetName + address;
    },
    // 根据id获取推广员
    promoterName() {
      if (this.dataInfo.promoterId && this.roleList.length > 0) {
        return this.roleList.find((item) => item.id == this.dataInfo.promoterId).name;
      }
    },
    // 根据id获取维护员
    keeperName() {
      if (this.dataInfo.keeperId && this.roleList.length > 0) {
        return this.roleList.find((item) => item.id == this.dataInfo.keeperId).name;
      }
    },
  },
  async mounted() {
    this.fetchObtainPlatformMerchants();
  },

  methods: {
    // 获取平台商户
    fetchObtainPlatformMerchants() {
      BusinessApi.listIdNameVo({businessType: 3}).then((res) => {
        if (res.data.length > 0) {
          this.platformMerchantList = res.data;
          this.sharingRatioBusinessList = res.data.filter((item) => item.id !== res.data[0].id);
          this.fetchObtainBusinessInfo(res.data[0].id);
        } else {
          Notification.error({title: '错误', message: '暂无平台商户信息', duration: 2 * 1000});
          this.returnList();
        }
      });
    },
    // 获得商户信息
    fetchObtainBusinessInfo(id) {
      BusinessApi.getBusinessInfo({id}).then((res) => {
        this.dataInfo = res.data;
        this.businessState = res.data.businessState === 1;
        this.servers = res.data.servers;
        this.accountInfo = res.data.accountInfo;
        this.businessVillages = res.data.businessVillages || [];
        this.banks = res.data.accountInfo.banks || [];
        this.sharingRatioForm.sharingBusinessId = res.data.sharingBusinessId || '';
        this.sharingRatioForm.proportion = res.data.proportion || '';
        this.sharingRatioForm.subsidyFlag = res.data.subsidyFlag !== null ? res.data.subsidyFlag : '';
        let serverClassifyIds = res.data.serverClassifyIds;
        this.formatBanners(res.data.banners);
        // 获取服务列表的id和name
        ServerClassifyApi.listIdName().then((res) => {
          let list = res.data;
          if (this.serverList && typeof this.serverList === 'string') {
            if (this.serverList.includes(',')) {
              this.serverList = this.serverList.split(',');
            } else {
              // 如果没有逗号，可以选择将其转换为单元素数组
              this.serverList = [this.serverList];
            }
          }
          serverClassifyIds.forEach((item) => {
            list.find((item2) => {
              if (item == item2.id) {
                this.serverList.push(item2.name);
                return true;
              }
            });
          });
          this.serverList = this.serverList.join(',');
        });

        // 获取推广员与维护员列表，两个取同一个列表
        LoginApi.roleInfoList().then((res) => {
          this.roleList = res.data;
        });

        // 经营时间
        if (res.data.businessBeginHours) {
          this.dataInfo.businessHours = res.data.businessBeginHours + '-' + res.data.businessEndHours;
        } else {
          this.dataInfo.businessHours = '';
        }

        // 划分设备地址和联系地址
        this.businessVillages.forEach((item) => {
          if (item.houseName) {
            let arr = item.houseName.split('-');
            item.linkName = arr[0];
            item.linkPhone = arr[1];
          }
        });
      });
    },
    getImgUrlList(list) {
      return list.map((item) => item.url);
    },
    formatBanners(banners) {
      const arr = [];
      banners.forEach((item) => {
        const index = arr.findIndex((item2) => item2.list.some((item3) => item3.serverClassifyId == item.serverClassifyId));
        if (index != -1) {
          arr[index].list.push(item);
        } else {
          arr.push({
            serverClassifyId: item.serverClassifyId,
            serverClassifyName: item.serverClassifyName,
            list: [item]
          });
        }
      });
      this.banners = arr;
    },
    formatVoiceFlag(cellValue) {
      if (cellValue === 0) {
        return '无';
      } else if (cellValue === 1) {
        return '普通商户';
      } else if (cellValue === 2) {
        return '平台商户';
      }
    },
    formatVillageType(cellValue) {
      if (cellValue === 1) {
        return '专属';
      } else if (cellValue === 2) {
        return '小区';
      } else if (cellValue === 3) {
        return '公里数';
      } else if (cellValue === 4) {
        return '地区';
      }
    },
    formatBusinessState(cellValue) {
      if (cellValue === 0) {
        return '未开通';
      } else if (cellValue === 1) {
        return '营业';
      } else if (cellValue === 2) {
        return '打烊';
      }
    },
    formatBusinessStates(cellValue) {
      if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      } else if (cellValue === 2) {
        return 'warning';
      }
    },
    formatOpenState(val) {
      switch (val) {
        case 1:
          return '待开户';
        case 2:
          return '开户审核中';
        case 1:
          return '开户成功';
        case 2:
          return '开户失败';
      }
    },
    formatManageType(type) {
      switch (type) {
        case 1:
          return '平台';
        case 2:
          return '托管平台运营';
        case 3:
          return '独立运营';
      }
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.back();
      // this.$router.push({path: '/business/businessManagement'})
    },
    handleChangeBusinessState() {
      this.$confirm(this.businessState ? '确定营业吗?' : '确定打烊吗?', '提示', {})
          .then((res) => {
            let params = {businessId: this.dataInfo.businessId, businessState: this.businessState ? 1 : 2};
            BusinessApi.setBusinessState(params).then((res) => {
              this.$Utils.notifySuccess('操作成功!');
            });
          }).catch(() => {
        this.businessState = !this.businessState;
      })
    },
    // 前往路由
    handleNavigateToRoute(type) {
      switch (type) {
        case '新增':
          this.$router.push({path: '/business/platformBusinessAdd', query: {}});
          break;
        case '编辑':
          this.$router.push({path: '/business/platformBusinessEdit', query: {id: this.dataInfo.businessId}});
          break;
        case '货品库':
          this.$router.push({path: '/goods/businessServerManagement', query: {businessId: this.dataInfo.businessId}});
          break;
        case '查看经营产品':
          this.$router.push({path: '/goods/goodsManagement', query: {businessId: this.dataInfo.businessId}});
          break;
        case '收款账户':
          this.$router.push({path: '/business/businessAccount', query: {businessId: this.dataInfo.businessId}});
          break;
      }
    },
    // 设置权重
    handleWeight() {
      this.showWeight = true;
      BusinessApi.getBusinessWeight({businessId: this.dataInfo.businessId}).then((res) => {
        this.weight = res.data;
      });
    },
    setWeight() {
      if (this.weight || this.weight === 0) {
        this.$confirm('确定保存吗?', '提示', {}).then((res) => {
          let params = {businessId: this.dataInfo.businessId, weight: this.weight};
          BusinessApi.setBusinessWeight(params).then((res) => {
            this.showWeight = false;
            this.$Utils.notifySuccess('设置成功!');
          });
        });
      } else {
        this.$message({type: 'error', message: '请输入权重'});
      }
    },
    // 设置折扣
    operateDiscount(i) {
      //1 提交 2 取消
      if (i == 1) {
        if (!this.discountInfo.val) {
          this.$message({
            type: 'error',
            message: '请输入比例值',
          });
          return;
        }
        let loading = this.$loading({
          lock: true,
          text: '设置中...',
          // background: "rgba(0, 0, 0, 0.7)",
        });
        let data = {
          businessId: this.businessId,
          type: this.discountInfo.discountType,
        };
        this.discountInfo.discountType == 1 ? (data.discount = this.discountInfo.val) : (data.packageDiscount = this.discountInfo.val);
        BusinessApi.setDiscount(data)
            .then((res) => {
              loading.close();
              if (res.status == 0) {
                this.$Utils.notifySuccess('设置成功!');
                this.operateDiscount(2);
                this.listLoading = true;
                this.listData();
              }
            })
            .catch((err) => {
              loading.close();
            });
      } else {
        this.showDiscount = false;
        this.discountInfo = {
          val: '',
          discountType: 1,
        };
      }
    },
    // 开通账号
    handleClickOpenUser() {
      const {openUser} = this;
      openUser.phone = '';
      openUser.show = true;
    },
    confirmOpenUser() {
      const {openUser, dataInfo} = this;
      this.$refs.openUser.validate((res) => {
        if (res) {
          this.$confirm('是否开通商户账号？', message.TITLE_PROMPT, {}).then(() => {
            const params = {
              userName: openUser.userName,
              businessId: dataInfo.businessId,
              phone: openUser.phone,
            };
            BusinessApi.openBusiness(params).then((res) => {
              openUser.show = false;
              this.listData();
              this.$Utils.notifySuccess('开通成功');
            });
          });
        }
      });
    },
    closeOpenUser() {
      this.openUser.show = false;
    },
    // 查看账号信息
    handleClickBusinessAccount() {
      BusinessApi.getBusinessAccount({businessId: this.dataInfo.businessId}).then((res) => {
        this.businessAccount.show = true;
        this.businessAccount.list = res.data || [];
      });
    },
    handleResetPassword(row) {
      this.$confirm('是否重置密码', message.TITLE_PROMPT, {}).then(() => {
        AuthApi.resetUserPwd({userId: row.userId}).then((res) => {
          this.$Utils.notifySuccess('重置密码成功');
        });
      });
    },
    // 关联公共服务员
    handleAssoicateWaiter() {
      const {waiter} = this;
      BusinessApi.listRelationData({businessId: this.dataInfo.businessId}).then((res) => {
        waiter.show = true;
        waiter.waiterId = res.data.map((item) => item.id);
      });
    },
    confirmAssoicateWaiter() {
      const {waiter, dataInfo} = this;
      const params = {
        ids: waiter.waiterId,
        id: dataInfo.businessId,
      };
      BusinessApi.batchSetRelation(params).then(() => {
        waiter.show = false;
        this.$Utils.notifySuccess('关联成功');
      });
    },
    // 设置管理范围
    async handleSetAddress() {
      const {setAddress, dataInfo} = this;
      setAddress.level = dataInfo.businessType == 3 && dataInfo.detailType == 1 ? 3 : 5;
      const res = await AdminVillageApi.listVillage({
        businessId: dataInfo.businessId,
      });
      setAddress.list = res.data || [];
      setAddress.show = true;
    },
    async confirmSetAddress() {
      const {dataInfo, setAddress} = this;
      const params = {businessId: dataInfo.businessId, list: []};
      await this.$confirm('确认保存', '提示', {});
      setAddress.list.forEach((item) => {
        const obj = {...item};
        delete obj.villageList;
        params.list.push(Object.assign(obj, {levels: obj.villageId ? 5 : obj.levels}));
      });
      setAddress.show = false;
      await AdminVillageApi.setManagementScope(params);
      this.$Utils.notifySuccess('设置成功');
    },

    // 设置配送费模版
    async handleSetDeliveryModel() {
      const {businessId} = this.dataInfo;
      const {deliveryModel} = this;
      let res = await DeliveryModelApi.getRelationByBusiness({businessId});
      deliveryModel.list = [];
      res = res.data || [];
      let title = '';
      for (let item in res) {
        switch (item) {
          case '1':
            title = '专属';
            break;
          case '2':
            title = '小区';
            break;
          case '3':
            title = '公里数';
            break;
          case '4':
            title = '省市区';
            break;
        }
        deliveryModel.list.push({
          title,
          list: res[item],
        });
      }
      let res2 = await DeliveryModelApi.listIdName({businessId});
      deliveryModel.modelList = res2.data;
      deliveryModel.show = true;
    },
    confirmSetDM() {
      const {deliveryModel} = this;
      const params = {
        list: deliveryModel.list
            .flatMap((item) => item.list)
            .map((item) => ({
              businessVillageId: item.businessVillageId,
              modelId: item.modelId,
            })),
      };

      DeliveryModelApi.setRelation(params).then((res) => {
        this.$Utils.notifySuccess();
        deliveryModel.show = false;
      });
    },
    // 上架该商户所有产品
    handleClickUpAllGoods() {
      this.$confirm('是否上架该商户所有产品？', message.TITLE_PROMPT, {}).then(() => {
        GoodsApi.startUsingGoods({businessId: this.dataInfo.businessId}).then((res) => {
          this.listData();
          this.$Utils.notifySuccess();
        });
      });
    },

    async handleConfirmSharingRatio() {
      this.$refs.sharingRatioForm.validate(async (valid) => {
        if (valid) {
          this.$confirm('确认保存', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            BusinessApi.setSharingInfo({...this.sharingRatioForm, businessId: this.dataInfo.businessId}).then(() => {
              this.$Utils.notifySuccess('设置成功');
              this.showSharingRatio = false;
              this.fetchObtainBusinessInfo(this.dataInfo.businessId);
            });
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>@import '@/assets/css/views/detailType.scss';</style>
